package org.codingq92.basic.io.bio;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;

/**
 * BIO传输文件的处理线程
 *
 * @author: CodingQ92
 * @date: 2025/6/24 21:58
 */
public class BIOServerHandler extends Thread {
    private Socket socket;

    public BIOServerHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            DataInputStream dis = new DataInputStream(inputStream);
            // 读取文件类型
            String fileType = dis.readUTF();
            String fileName = "/Users/smyxmac/Documents/workspace/ideaSpace/HandWritten/src/main/resources/" + UUID.randomUUID() + "." + fileType;
            System.out.println(socket.getRemoteSocketAddress() + "开始传输>>>> 文件类型" + fileType);
            // 读取文件内容
            OutputStream outputStream = new FileOutputStream(fileName);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = dis.read(bytes)) > -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.close();
            System.out.println(socket.getRemoteSocketAddress() + "传输完成<<<<");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

